package com.lxs.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.lxs.common.constant.ProductConstant;
import com.lxs.common.utils.PageUtils;
import com.lxs.common.utils.Query;
import com.lxs.mall.product.dao.AttrAttrgroupRelationDao;
import com.lxs.mall.product.entity.AttrAttrgroupRelationEntity;
import com.lxs.mall.product.entity.AttrGroupEntity;
import com.lxs.mall.product.entity.CategoryEntity;
import com.lxs.mall.product.service.AttrAttrgroupRelationService;
import com.lxs.mall.product.service.AttrGroupService;
import com.lxs.mall.product.service.CategoryService;
import com.lxs.mall.product.vo.AttrGroupRelationVO;
import com.lxs.mall.product.vo.AttrResponseVo;
import com.lxs.mall.product.vo.AttrVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collector;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.lxs.mall.product.dao.AttrDao;
import com.lxs.mall.product.entity.AttrEntity;
import com.lxs.mall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    CategoryService categoryService;
    @Autowired
    AttrGroupService attrGroupService;
    @Resource
    AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Autowired
    AttrAttrgroupRelationService attrAttrgroupRelationService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryBasePage(Map<String, Object> params, Long catelogId, String attrType) {
        QueryWrapper<AttrEntity> wrapper =new QueryWrapper<>();
        wrapper.eq("attr_type","base".equalsIgnoreCase(attrType)?1:0);
        //1，根据类别编号进行查询
        if(catelogId!=0){
            wrapper.eq("catelog_id",catelogId);
        }
        //2,根据key进行模糊查询
        String  key = (String) params.get("key");
        if(StringUtils.isNotEmpty(key)){
            wrapper.and((w)->w.eq("attr_id",key).or().like("attr_name",key));
        }
        //3,分页查询
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        //4,关联的我们需要查询出的类别名称和属性组名称
        List<AttrEntity> records = page.getRecords();
        List<AttrResponseVo> list = records.stream().map((attrEntity) -> {
            AttrResponseVo attrResponseVo = new AttrResponseVo();
            BeanUtils.copyProperties(attrEntity,attrResponseVo);
            CategoryEntity categoryEntity = categoryService.getById(attrEntity.getCatelogId());
            if(categoryEntity!=null){
                attrResponseVo.setCatelogName(categoryEntity.getName());
            }
            if("base".equalsIgnoreCase(attrType)){
                AttrAttrgroupRelationEntity entity = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_id", attrEntity.getAttrId()));
                if(entity!=null&&entity.getAttrGroupId()!=null){
                    //根据属性组Id 查找对应的组名
                    AttrGroupEntity groupEntity = attrGroupService.getById(entity.getAttrGroupId());
                    if(groupEntity!=null&& StringUtils.isNotEmpty(groupEntity.getAttrGroupName())){
                        attrResponseVo.setGroupName(groupEntity.getAttrGroupName());
                    }
                }
            }
            return attrResponseVo;
        }).collect(Collectors.toList());
        pageUtils.setList(list);
        return pageUtils;
    }
    @Transactional
    @Override
    public void saveAttr(AttrVO attrVo) {
        //1,保存规格参数的正常信息
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo,attrEntity);
        this.save(attrEntity);
        //2,保存规格参数和组对应的关系信息
        if(attrVo.getAttrGroupId()!=null&&attrVo.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            //设置相关的属性
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            //将关联的数据保存到对应的表结构中去
            attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);
        }

    }

    @Override
    public AttrResponseVo getAttrInfo(Long attrId) {
        AttrResponseVo attrResponseVo = new AttrResponseVo();

        //1,查询规格参数的基本信息
        AttrEntity attrEntity= this.getById(attrId);
        BeanUtils.copyProperties(attrEntity,attrResponseVo);
        //2,根据attrId 查询对应的属性组的相关信息
        AttrAttrgroupRelationEntity entity = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                .eq("attr_id", attrEntity.getAttrId()));
        if(entity!=null){
            //根据属性组Id 查找对应的组名
            AttrGroupEntity groupEntity = attrGroupService.getById(entity.getAttrGroupId());
            attrResponseVo.setAttrGroupId(groupEntity.getAttrGroupId());
            if(groupEntity!=null&& StringUtils.isNotEmpty(groupEntity.getAttrGroupName())){
                attrResponseVo.setGroupName(groupEntity.getAttrGroupName());
            }
        }
        //查询关联的类别信息
        Long catelogId= attrEntity.getCatelogId();
        Long[]catelogPath= categoryService.findCatelogPath(catelogId);
        attrResponseVo.setCatelogPath(catelogPath);
        CategoryEntity categoryEntity = categoryService.getById(catelogId);
        if(categoryEntity!=null){
            attrResponseVo.setCatelogName(categoryEntity.getName());
        }


        return attrResponseVo;
    }
    @Transactional
    @Override
    public void updateBaseAttr(AttrVO attr) {
        AttrEntity attrEntity=new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        //1，更新基本的数据信息
        this.updateById(attrEntity);
        if(attr.getAttrType()== ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            //修改分组的关联信息
            // 2.修改分组关联的关系
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            AttrAttrgroupRelationEntity groupRelationEntity = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attr.getAttrId()));
            if(groupRelationEntity==null){
                attrAttrgroupRelationService.save(relationEntity);
            }else{
                attrAttrgroupRelationService.update(relationEntity,new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attr.getAttrId()));
            }
        }


    }

    @Override
    public void removeByIdsDetails(List<Long> attrIds) {
        for (Long attrId : attrIds) {
            AttrEntity attrEntity= this.getById(attrId);
            if(attrEntity!=null&&attrEntity.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
                attrAttrgroupRelationService.remove(new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrId));
            }
        }
        this.removeBatchByIds(attrIds);
    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        //1,根据属性组编号查询属性和组关联信息表中对应的属性信息、
        List<AttrAttrgroupRelationEntity>list = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id",attrgroupId));
        //2,根据属性编号查询属性表中对应的属性的详细信息
        List<AttrEntity> attrEntities = list.stream().map((entity) -> this.getById(entity.getAttrId()))
                .filter((entity) -> entity != null)
                .collect(Collectors.toList());
        return attrEntities;

    }

    @Override
    public void relationDelete(AttrGroupRelationVO[] vos) {
        //将我们接受的对象转为一个实体对象
        List<AttrAttrgroupRelationEntity> relationEntities = Arrays.asList(vos).stream().map((item) -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item,relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());
        attrAttrgroupRelationDao.removeBatchRelation(relationEntities);
    }

    @Override
    public PageUtils getNoAttrRelation(Map<String, Object> params, Long attrgroupId) {
        //1，查询当前属性组所在的类别编号
        AttrGroupEntity attrGroupEntity=attrGroupService.getById(attrgroupId);
        //2,根据类别编号查询出该类别下对应的所有属性组编号
        List<Long> attrGroupIds = attrGroupService.list(
                new QueryWrapper<AttrGroupEntity>().eq("catelog_id",attrGroupEntity.getCatelogId()))
                .stream().map((e)->e.getAttrGroupId()).collect(Collectors.toList());
        //3,查询该类别下的所有的属性组已经分配的属性信息
        List<Long> attrIds = attrAttrgroupRelationService.list(
                new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", attrGroupIds)).stream()
                .map((e) -> e.getAttrId()).collect(Collectors.toList());
        //4,查询该类别下的所有（排除掉已分配的和销售属性的）基本属性信息，并分页处理
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>()
                .eq("catelog_id", attrGroupEntity.getCatelogId())
                .eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if(!CollectionUtils.isEmpty(attrIds)){
            wrapper.notIn("attr_id", attrIds);
        }
        String key = (String) params.get("key");
        if(StringUtils.isNotEmpty(key)){
            wrapper.and(e->e.like("attr_id",key).or().like("attr_name",key));
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public List<Long> selectSearchAttrIds(List<Long> attrIds) {
        List<AttrEntity> attrEntities= this.list(new QueryWrapper<AttrEntity>()
                .in("attr_id",attrIds).eq("search_type",1));
        List<Long> collect = attrEntities.stream().map(attrEntity -> attrEntity.getAttrId()).collect(Collectors.toList());
        return collect;
    }

}
